package de.unikiel.jmeter;

import net.sourceforge.jeval.Evaluator;

import org.apache.jmeter.engine.event.LoopIterationEvent;
import org.apache.jmeter.testelement.AbstractTestElement;
import org.apache.jmeter.testelement.TestListener;
import org.apache.jmeter.testelement.ThreadListener;
import org.apache.jmeter.timers.Timer;
import org.apache.jmeter.util.JMeterUtils;

public class FunctionTimer extends AbstractTestElement implements Timer,
		TestListener, ThreadListener {

	/**
	 * 
	 */
	private static final long serialVersionUID = -126642672301682052L;
	private volatile long starttime = -1;

	public FunctionTimer() {
	}

	@Override
	public long delay() {
		try {
			starttime = Long.parseLong(JMeterUtils.getProperty("starttime"));
			final double t = System.currentTimeMillis() - starttime;
			final Evaluator evaluator = (Evaluator) getThreadContext()
					.getVariables().getObject("eval");
			evaluator.putVariable("t", t + "");
			final double result = evaluator
					.getNumberResult(getPropertyAsString("expression"));
			return (long) (result > 0 ? result : 0);
		} catch (final Exception e) {
			e.printStackTrace();
			return 0;
		}
	}

	@Override
	public void testEnded() {
	}

	@Override
	public void testEnded(final String arg0) {
	}

	@Override
	public void testIterationStart(final LoopIterationEvent arg0) {
	}

	@Override
	public void testStarted() {
		JMeterUtils.setProperty("starttime", System.currentTimeMillis() + "");

	}

	@Override
	public void testStarted(final String arg0) {
		testStarted();
	}

	@Override
	public void threadFinished() {
		// TODO Auto-generated method stub

	}

	@Override
	public void threadStarted() {
		final Evaluator evaluator = new Evaluator();
		try {
			evaluator.parse(getPropertyAsString("expression"));
		} catch (final Exception e) {
			e.printStackTrace();
		}
		getThreadContext().getVariables().putObject("eval", evaluator);
	}

}
